package com.dyt.itool.parser;

import java.io.File;
import java.util.*;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.dyt.itool.generator.CHelper;
import com.dyt.itool.generator.JavaHelper;
import com.dyt.itool.generator.LuaHelper;
import com.dyt.itool.generator.VelocityUtils;


public class ErrorParser {
	
	private static Logger logger = Logger.getLogger( ErrorParser.class );
	
	private List<ErrorInfo> errorList = new ArrayList<ErrorInfo>( );
	
	
	public void parseErrors( String errorXmlFile ){
	
		File f = new File( errorXmlFile );
		if( !f.exists()  || !f.isFile( ) ){
			logger.debug( "要解析的文件不存在" );
			return;
		}
		
		SAXReader saxReader = new SAXReader( );
		Document dom;
		try {
			dom = saxReader.read( f );
		} catch (DocumentException e) {
			e.printStackTrace();
			logger.debug( e.getMessage() );
			return;
		}
		
		Element root = dom.getRootElement( );
		
		parseErrors( root );
	}
	
	
	public void generateErrorCode(String templateFile,String outputFile ) {
		
		Map<String, Object> dataMap = new HashMap<String,Object >( );
		dataMap.put( "errorList", this.errorList );
		
		dataMap.put( "javautil", new JavaHelper() );
		dataMap.put( "cutil", new CHelper() );
		dataMap.put( "luautil", new LuaHelper() );
		
		VelocityUtils.generateFromVelocity( templateFile , outputFile,  dataMap );
		
	}	
	
	
	
	@SuppressWarnings("unchecked")
	private void parseErrors( Element root ){
		
		 List<Element> errorElements = root.elements( "error" );
		 for( Element element : errorElements){
			 ErrorInfo error = new ErrorInfo();
			 error.setErrorid( element.attributeValue( "id" ) );
			 error.setDesc( element.attributeValue( "desc" ) ) ;
			 error.setName( element.attributeValue( "name" ) );
			 errorList.add( error );
		 }
		 
	}
	
	
	
}
